<template>
    <div>
        <div id="navigator_container" class="flex-container">
            <div>
                <span>聘途</span>
                <div id="address">
                    <el-avatar :src="userInfo.avatar" :size="30" @click.native="changeAvatar"></el-avatar>
                    <span>{{ address }}</span>
                    <button @click="changeAddress">&#91;切换&#93;</button>
                </div>
            </div>
            <div id="navigator">
                <el-menu :default-active="activePath" class="el-menu-demo" mode="horizontal" @select="handleSelect"
                    background-color=transparent text-color="#fff" style="border: none;">
                    <el-menu-item v-for="item in navigat" :key="item.id" :index="item.path" class="custom-menu-item">
                        {{ item.name }}
                    </el-menu-item>
                </el-menu>
            </div>
            <div id="my">
                <el-menu mode="horizontal" class="custom-menu" background-color="transparent" text-color="#fff"
                    style="border: none;">

                    <el-menu-item index="chat" @click="chat" style="width: 100px;">

                        <i class="el-icon-message"></i> 消息
                    </el-menu-item>

                    <el-menu-item index="cv" @click="cv">
                        <i class="el-icon-document"></i> 简历
                    </el-menu-item>

                    <el-submenu index="user">
                        <template #title>
                            <i class="el-icon-user"></i>
                            <span style="font-size: 14px;">我的</span>
                        </template>
                        <el-menu-item index="profile" class="custom-submenu-item" @click="personal">个人中心</el-menu-item>
                        <el-menu-item index="security" class="custom-submenu-item"
                            @click="changePassword">修改密码</el-menu-item>
                        <el-menu-item index="terms" class="custom-submenu-item"
                            @click="changePhone">修改手机号</el-menu-item>
                        <el-menu-item index="logout" @click="logout" class="custom-submenu-item">退出登录</el-menu-item>
                    </el-submenu>
                </el-menu>
            </div>

            <!-- 隐藏的文件选择器 -->
            <input ref="fileInput" type="file" accept="image/*" style="display: none" @change="handleFileSelect">
        </div>

        <PasswordResetModal ref="passwordResetModal" @close="closePasswordResetModal" v-if="showPasswordModal"
            :visible="showPasswordModal" @submit="handlePasswordReset" />

        <phone-update-modal :visible.sync="showPhoneModal" @submit="handlePhoneUpdate"
            @cancel="showPhoneModal = false"></phone-update-modal>


        <LocationSelector v-if="showCityModal" :mode="1" :visible.sync="showCityModal" @change="handleCityChange"
            @confirm="handleCityConfirm" @close="showCityModal = false" />

        <div id="content">
            <router-view></router-view>
        </div>
    </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';

import LocationSelector from '@/components/localSelect.vue'
import PasswordResetModal from '@/views/SeekerViews/components/updataPassword.vue';
import { changePassword, changePhoneNum, uploadAvatar } from '@/util/seeker_api/Person_api';


import PhoneUpdateModal from '@/views/SeekerViews/components/updataPhone.vue';

export default {
    components: {
        LocationSelector,
        PasswordResetModal,
        PhoneUpdateModal


    },
    data() {
        return {
            navigat: [
                { id: 1, name: '首页', path: '/home' },
                { id: 2, name: '职位', path: '/job' },
                { id: 3, name: '公司', path: '/seekerCompany' },
            ],
            showCityModal: false,
            searchCity: '',
            showPasswordModal: false,
            showPhoneModal: false,
            activePath: '',
            isUploading: false // 上传状态
        }
    },
    methods: {
        changeAddress() {
            this.showCityModal = true;
        },
        handleCityChange(selectedCity) {
            if (!selectedCity) return;
            this.$store.dispatch('seeker/setAddress', selectedCity);
        },
        handleCityConfirm(selectedCity) {
            this.handleCityChange(selectedCity);
            this.showCityModal = false;
        },
        handleSelect(index) {
            this.$router.push(index);
        },
        chat() {
            this.$router.push('/chat');
        },
        cv() {
            this.$router.push('/cv'); // 修改为正确的路由路径
        },
        personal() {
            this.$router.push('/personal');
        },
        logout() {
            this.$store.dispatch('seeker/logout');
        },
        changePassword() {
            this.showPasswordModal = true;

        },
        async handlePasswordReset(formData) {
            const data = {
                phone: formData.phone,
                oldPassword: formData.oldPassword,
                newPassword: formData.newPassword,
            }

            try {
                const response = await changePassword(data);
                this.$message.success('密码修改成功');
                this.showPasswordModal = false;
            } catch (error) {
                console.error('修改密码失败:', error);
                this.$message.error('密码修改失败: ' + error.message);
            } finally {
                this.logout();
            }
        },

        closePasswordResetModal() {
            this.showPasswordModal = false;
        },
        changePhone() {
            this.showPhoneModal = true;
        },
        async handlePhoneUpdate(formData) {

            const data = {
                oldPhone: formData.oldPhone,
                newPhone: formData.newPhone,
                password: formData.password,
            }

            try {
                const response = await changePhoneNum(data);
                console.log('修改手机号成功:', response);
                this.$message.success('手机号修改成功');
                this.showPhoneModal = false;
            } catch (error) {
                console.error('修改手机号失败:', error);
                this.$message.error('手机号修改失败: ' + error.message);
            } finally {
                this.logout();
            }
        },
        closePhoneUpdateModal() {
            this.showPhoneModal = false;
        },
        changeAvatar() {

            if (!this.isUploading) {
                this.$refs.fileInput.click();
            }
        },
        // 处理文件选择
        handleFileSelect(e) {
            const file = e.target.files[0];
            if (!file) return;

            // 验证文件类型
            if (!file.type.startsWith('image/')) {
                this.$message.error('请选择图片文件');
                e.target.value = '';
                return;
            }

            // 验证文件大小（限制5MB）
            if (file.size > 5 * 1024 * 1024) {
                this.$message.error('图片大小不能超过5MB');
                e.target.value = '';
                return;
            }

            // 上传文件
            this.uploadAvatar(file);

            // 重置文件选择器（解决重复选择同文件不触发事件问题）
            e.target.value = '';
        },
        // 上传头像到后端
        // 上传头像（适配MultipartFile类型）
        async uploadAvatar(file) {
            try {
                this.isUploading = true;

                // 创建FormData对象，用于传递文件
                const formData = new FormData();
                // 这里的key为"file"，需与后端接收MultipartFile的参数名一致
                formData.append('file', file);
                const response = await uploadAvatar(formData);
                console.log('上传头像成功:', response);

                const token = response.data.data;
                this.$store.dispatch('seeker/updateToken', token);

                this.$message.success('头像上传成功');




            } catch (error) {
                console.error('头像上传错误:', error);
                this.$message.error('上传失败，请稍后重试');
            } finally {
                this.isUploading = false;
            }
        },







    },
    computed: {
        ...mapState({
            userInfo: state => state.seeker.userInfo,
            address: state => state.seeker.address,
        })
    },
}
</script>


<style scoped>
/* 全局样式重置（可选，根据项目需求） */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.flex-container {
    display: flex;
    width: 100%;
}

body {
    font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
    background: linear-gradient(180deg, rgba(65, 150, 141, 0.15) 0%, #f3f5f7 100%);
}

/* 导航容器 */
#navigator_container {
    width: 100%;
    background: linear-gradient(90deg, #41968d 0%, #026e62 100%);
    color: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
}

.custom-menu-item{
    margin: 0 20px;
    width: 100px;

}

.el-menu-demo{
    padding: 0 20px;

}

/* 菜单项悬停样式 */
.custom-menu .el-menu-item:hover {
    color: #409EFF;
}

/* 激活菜单项样式 */
.custom-menu .el-menu-item.is-active {
    color: #409EFF;
    background-color: rgba(64, 158, 255, 0.08);
}

/* 移除底部边框 */
.custom-menu::after {
    display: none;
}

#navigator_container>div {
    display: flex;
    align-items: center;
}



/* 左侧标题与地址区域 */
#navigator_container>div:first-child {
    gap: 20px;
}

#navigator_container span:first-child {
    font-size: 24px;
    font-weight: bold;
    cursor: pointer;
}

#navigator{
    width: 33%;
    display: flex;
    align-items: center;
    gap: 20px;

}

/* 地址模块 */
#address {
    display: flex;
    align-items: center;
    gap: 8px;
}

#address img {
    width: 24px;
    height: 24px;
    object-fit: cover;
}

#address button {
    background-color: transparent;
    color: #fff;
    border: 1px solid #fff;
    border-radius: 4px;
    padding: 4px 8px;
    cursor: pointer;
    transition: all 0.3s ease;
}

#address button:hover {
    background-color: #fff;
    color: #009688;
}

/* 子菜单项样式 */
.custom-submenu-item {
    color: #333 !important;
}



/* 城市选择弹窗（保留原有，可微调） */
.city-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.city-modal-content {
    background: white;
    width: 80%;
    max-width: 800px;
    max-height: 80vh;
    border-radius: 8px;
    overflow: hidden;
}

.city-modal-header {
    padding: 15px;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.search-box input {
    padding: 8px;
    width: 200px;
    border: 1px solid #ddd;
    border-radius: 4px;
}

.close {
    cursor: pointer;
    font-size: 24px;
}

.city-modal-body {
    padding: 20px;
    max-height: calc(80vh - 60px);
    overflow-y: auto;
}

.city-section {
    margin-bottom: 20px;
}

.city-list {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-top: 10px;
}

.city-item {
    padding: 5px 15px;
    border: 1px solid #ddd;
    border-radius: 4px;
    cursor: pointer;
}

.city-item:hover {
    background-color: #f5f5f5;
}

.letter-index {
    display: flex;
    gap: 8px;
    margin-bottom: 15px;
    flex-wrap: wrap;
}

.letter-item {
    cursor: pointer;
    padding: 2px 6px;
}

.letter-item:hover {
    color: #1890ff;
}

.cities-by-letter {
    max-height: 400px;
    overflow-y: auto;
}

.cities-by-letter h3 {
    margin: 10px 0;
    padding-top: 10px;
    border-top: 1px solid #eee;
}

/* 内容容器 */
#content {
    width: 90%;
    max-width: 1200px;
    margin: 20px auto;
    background: transparent;
    border-radius: 8px;
    min-height: calc(100vh - 120px);
    padding: 20px;
}
</style>